package org.paradise.dms.dao.impl;

import java.io.File;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.paradise.dms.util.DateUtil;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Service;

import com.dheaven.framework.dao.BaseHibernateDao;

@SuppressWarnings("unchecked")
@Service
public class DBBackupDAOImpl extends BaseHibernateDao {

	@SuppressWarnings("unused")
	private static Logger log = Logger.getLogger(DormitoryDAOImpl.class);

	/**
	 * Description: 备份数据库中所有表的信息
	 * 
	 * @Version1.0 2009-5-11 下午00:00:20 闫克（kurtyan777@gmail.com）创建
	 */
	public String backupDB() {
		return (String) this.getHibernateTemplate().execute(new HibernateCallback() {
			public String doInHibernate(Session session) {
				String path = makeDir();
				log.info(path);
				// 列出数据库中所有表
				SQLQuery query = (SQLQuery) session.createSQLQuery("show tables");
				List tableList = query.list();
				for (int i = 0; i < tableList.size(); i++) {
					log.info(tableList.get(i) + "");
					String bkupsql = "select * from " + tableList.get(i) + " into outfile '" + path + "/" + tableList.get(i) + ".sql'";
					SQLQuery bkupquery = (SQLQuery) session.createSQLQuery(bkupsql);
					try {
						// select into outfile语句并不返回数据 而此时执行list方法的话会抛出resultset
						// empty异常导致程序中断
						// 但实际上即使抛出了异常，该select语句也会成功执行
						bkupquery.list();
					} catch (HibernateException e) {
					}
				}
				return "数据库已经成功备份在服务器" + path + " 文件夹下";
			}
		});
	}

	/**
	 * 
	 * Description:
	 * 在系统的C盘下建立一个以当前时间为C:/DMS_DB_Back_2009-05-14_1242238433697为格式的文件夹，用于存放保存的数据库
	 * 
	 * @Version1.0 May 14, 2009 2:04:35 AM 李双江（paradise.lsj@gmail.com）创建
	 * @return
	 */

	public static String makeDir() {
		File dirFile = null;
		Date d = new Date();
		String path = "C:/DMS_DB_Back_" + DateUtil.format(d, DateUtil.C_DATE_PATTON_DEFAULT) + "_" + d.getTime();
		try {
			dirFile = new File(path);
			if (!(dirFile.exists()) && !(dirFile.isDirectory())) {
				boolean creadok = dirFile.mkdirs();
				if (creadok) {
					log.info(" ok:创建文件夹成功！ ");
					return path;
				} else {
					log.info(" err:创建文件夹失败！ ");
					return null;
				}
			}
		} catch (Exception e) {
			log.error("DMS_error:创建保存数据库的文件夹失败,");
			log.error("失败原因" + e);
			return null;
		}
		return null;
	}

	public String restoreDB() {
		return (String) this.getHibernateTemplate().execute(new HibernateCallback() {
			@SuppressWarnings("unchecked")
			public String doInHibernate(Session session) {
				// 列出数据库中所有表
				SQLQuery query = (SQLQuery) session.createSQLQuery("show tables");
				List tableList = query.list();
				for (int i = 0; i < tableList.size(); i++) {
					System.out.println(tableList.get(i) + "");

					String truncatetable = "truncate table " + tableList.get(i);
					SQLQuery trunctablequery = (SQLQuery) session.createSQLQuery(truncatetable);
					trunctablequery.executeUpdate();

					// String bkupsql = "select * from " + tableList.get(i) + "
					// into outfile 'c:/" + tableList.get(i) + ".sql'";

					String restoresql = "load data infile 'c:/" + tableList.get(i) + ".sql' replace into table " + tableList.get(i);
					SQLQuery restorequery = (SQLQuery) session.createSQLQuery(restoresql);

					try {
						// select into outfile语句并不返回数据 而此时执行list方法的话会抛出resultset
						// empty异常导致程序中断
						// 但实际上即使抛出了异常，该select语句也会成功执行
						restorequery.list();
					} catch (HibernateException e) {
						e.printStackTrace();
					}
				}

				return "succeed";
			}
		});
	}

}
